<?php
namespace M\Controller;
use Think\Controller;

class UserapiController extends Controller{
    public function _initialize(){
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Methods:GET');
        header('Access-Control-Allow-Methods:POST');
        header('Access-Control-Allow-Headers:x-requested-with,content-type');
    }
    public function sendDayuSmsPlus($tel,$number)
    {
        $client = new \Message\Controller\TopClientController();
        $client->appkey = '23424421';
        $client->secretKey = '6f084da49143dfb0e46ae4daaf66fe3f';
        $req = new \Message\Controller\AlibabaAliqinFcSmsNumSendRequestController();
// 设置请求参数
        $req ->setSmsTemplateCode('SMS_12925564');
        $req ->setRecNum($tel);
        $url = "{\"num\":\"" . $number. "\"}";
        $req->setSmsParam($url);
        $req ->setSmsFreeSignName('威普极客');
        $req ->setSmsType('normal');
        $req ->setExtend('demo');

        $data= $client->execute($req);
        $arr=$this->xmlToArr($data);//将返回的xml解析成数组
        return $arr;
    }

    /**获取验证码
     * para: phonenumber
     * return:
     *  code
     *  msg
     */
    public function getPhoneCode(){
//        var_dump(session('18883986242'));
//        die;
        $phone=I('phonenumber');

        $code=D('Code');
        $phonecode=mt_rand(1000, 9999);//生成验证码


        $info=$this->sendDayuSmsPlus($phone,$phonecode) ;
//        var_dump($info['alibaba_aliqin_fc_sms_num_send_response']['result']['success']);
        if($info['alibaba_aliqin_fc_sms_num_send_response']['result']['success']==true )
        {
            if(!$code->create(I('get.')))//已存在数据库
            {
                $info=array(
                    'code'=>$phonecode,
                    'status'=>'1',//1代表可用
                    'time'=>date('Y-m-d H:i:s',time()+120)
                );
                M('code')->where(array('phonenumber'=>$phone))->save($info);
            }else {//不存在数据库
                $info=array(
                    'phonenumber'=>$phone,
                    'code'=>$phonecode,
                    'status'=>'1',//1代表可用
                    'time'=>date('Y-m-d H:i:s',time()+120)
                );
                M('code')->add($info);
            }

            $result=array(
                'code'=>'1',
                'msg'=>'获取手机验证码成功'
            );
        }else{
            $result=array(
                'code'=>'0',
                'msg'=>'获取手机验证码失败'
            );
        }
        echo json_encode($result,JSON_UNESCAPED_UNICODE);
    }

    public function xmlToArr ($xml, $root = true) {

        if (!$xml->children()) {
            return (string) $xml;
        }
        $array = array();
        foreach ($xml->children() as $element => $node) {
            $totalElement = count($xml->{$element});
            if (!isset($array[$element])) {
                $array[$element] = "";
            }
// Has attributes
            if ($attributes = $node->attributes()) {
                $data = array(
                    'attributes' => array(),
                    'value' => (count($node) > 0) ? $this->xmlToArr($node, false) : (string) $node
                );
                foreach ($attributes as $attr => $value) {
                    $data['attributes'][$attr] = (string) $value;
                }
                if ($totalElement > 1) {
                    $array[$element][] = $data;
                } else {
                    $array[$element] = $data;
                }
// Just a value
            } else {
                if ($totalElement > 1) {
                    $array[$element][] = $this->xmlToArr($node, false);
                } else {
                    $array[$element] = $this->xmlToArr($node, false);
                }
            }
        }
        if ($root) {
            return array($xml->getName() => $array);
        } else {
            return $array;
        }

    }


    /**用户注册
     * para:phonenumber,password,phonecode
     * return
     *  code
     *  msg
     */
    public function register(){
        $phonenumber=I('phonenumber');
        $password=I('password');
        $phonecode=I('phonecode');
        $time=date('YmdHis',time());
        $user=D('user');
        $code=M('code');

        if(!$user->create(I('get.')))
        {
            $data=array(
                'code'=>'2',
                'msg'=>$user->getError()
            );
        }else{

            $realCode=$code->where(array('phonenumber'=>$phonenumber))->field('code,time,status')->find();
            if(strtotime($realCode['time'])-time() <= 0)//过时失效
            {
                $code->where(array('phonenumber'=>$phonenumber))->save(array('status'=>'0'));
                $realCode['status']='0';
            }
            if($realCode['status']!='1')
            {
                $data=array(
                    'code'=>'0',
                    'msg'=>'验证码已失效'
                );
                echo json_encode($data,JSON_UNESCAPED_UNICODE);
                exit;
            }

            if($realCode['code']==$phonecode )
            {
                $info=array(
                    'id'=>md5($time),
                    'password'=>md5($password),
                    'phonenumber'=>$phonenumber,
                    'time'=>$time
                );
                M('user')->add($info);
                $code->where(array('phonenumber'=>$phonenumber))->save(array('status'=>'0'));
                $data=array(
                    'code'=>'1',
                    'msg'=>'用户注册成功'
                );
            }else{
                $data=array(
                    'code'=>'3',
                    'msg'=>'验证码错误'
                );
            }

        }
        echo json_encode($data,JSON_UNESCAPED_UNICODE);

    }

    /**登录
     * para:phonenumber,password
     * reuturn:
     *  code 1、成功 0、失败
     *  msg
     *  token
     *  user_id
     */
    public function login(){
        $phonenumber=I('phonenumber');
        $password=I('password');
        if(!empty($phonenumber) && !empty($password))
        {
            $result=M('user')->where(array('phonenumber'=>$phonenumber))->field('id,password')->find();
            if($result!='' && md5($password)==$result['password'])
            {
                $data=array(
                    'code'=>'1',
                    'msg'=>'登陆成功',
                    'token'=>'',
                    'user_id'=>$result['id']
                );
            }else{
                $data=array(
                    'code'=>'0',
                    'msg'=>'手机号码或者密码错误'
                );
            }
        }else{
            $data=array(
                'code'=>'2',
                'msg'=>'请输入完整信息'
            );
        }
        echo json_encode($data,JSON_UNESCAPED_UNICODE);
    }

    /**忘记密码
     * para：phonenumber,phonecode, password
     * return:
     *  code
     *  msg
     *
     */
    public function forgetPassword(){
        $phonenumber=I('phonenumber');
        $phonecode=I('phonecode');
        $password=I('password');
        $user=M('user');
        $code=M('code');

        $realCode=$code->where(array('phonenumber'=>$phonenumber))->field('code,time,status')->find();
        if(strtotime($realCode['time'])-time() <= 0)//过时失效
        {
            $code->where(array('phonenumber'=>$phonenumber))->save(array('status'=>'0'));
            $realCode['status']='0';
        }
        if($realCode['status']!='1')
        {
            $data=array(
                'code'=>'0',
                'msg'=>'验证码已失效'
            );
            echo json_encode($data,JSON_UNESCAPED_UNICODE);
            exit;
        }

        if(!empty($phonecode) && $realCode['code']==$phonecode)
        {
            $flag=$user->where(array('phonenumber'=>$phonenumber))->getField('id');
            if(!empty($phonenumber) && $flag!='')
            {
                if(!empty($password))
                {
                    $user->password=md5($password);
                    $user->where(array('phonenumber'=>$phonenumber))->save();
                    $code->where(array('phonenumber'=>$phonenumber))->save(array('status'=>'0'));
                    $data=array(
                        'code'=>'1',
                        'msg'=>'修改成功'
                    );
                }else{
                    $data=array(
                        'code'=>'2',
                        'msg'=>'密码不能为空'
                    );
                }
            }else{
                $data=array(
                    'code'=>'3',
                    'msg'=>'电话号码有误'
                );
            }

        }else{
            $data=array(
                'code'=>'0',
                'msg'=>'验证码输入错误'
            );
        }
        echo json_encode($data,JSON_UNESCAPED_UNICODE);
    }
}